import java.util.Arrays;

public class 最短无序连续子数组 {

    /**
     * https://leetcode.cn/problems/shortest-unsorted-continuous-subarray/
     * @param nums
     * @return
     */

    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        if(n == 1){
            return 0;
        }
        int[] arr = nums.clone();
        Arrays.sort(arr);
        int i = 0;
        int j = n - 1;
        //找到左边界
        while(i < n && nums[i] == arr[i]){
            i++;
        }
        if (i == n) {
            return 0;
        }
        //找到右边界
        while(j >= 0 && nums[j] == arr[j]){
            j--;
        }
        return  j - i + 1;
    }
}
